#include "MyRpc.h"
#include <iostream>
#include <string>
#include <getopt.h>

RpcConfig MyRpc::config_;

void ShowCommandHelp()
{
    // std::cout << "format: command -i <configfile>" << std::endl;
    LOG_INFO("format: command -i <configfile>");
}

void MyRpc::Init(int argc, char **argv)
{
    // std::cout << "MyRpc::Init()" << std::endl;
    LOG_INFO("MyRpc::Init()");

    // argc不能小于2
    if (argc < 2)
    {
        ShowCommandHelp();
        exit(EXIT_FAILURE);
    }

    // 解析命令行参数
    int c;
    std::string configfile;
    while ((c = getopt(argc, argv, "i:")) != -1)
    {
        switch (c)
        {
        case 'i':
            configfile = optarg;
            break;
        case '?':
            // std::cout << "unknown option: " << optopt << std::endl;
            LOG_ERROR("unknown option: %d", optopt);
            exit(EXIT_FAILURE);
        case ':':
            // std::cout << "invaild args" << std::endl;
            LOG_ERROR("invaild args");
            exit(EXIT_FAILURE);
        default:
            break;
        }
    }

    // 加载配置文件
    if(configfile.empty())
    {
        // std::cout << "configfile is empty" << std::endl;
        LOG_ERROR("configfile is empty");
        exit(EXIT_FAILURE);
    }
    config_.LoadConfigFile(configfile);

    // 打印配置文件内容
    config_.PrintConfig();
}

MyRpc &MyRpc::GetInstance()
{
    static MyRpc MyRpc;
    return MyRpc;
}

RpcConfig &MyRpc::GetConfig() {
    return config_;
}